package com.example.demo.service;

import com.example.informationmanagement.entity.Information;
import com.example.informationmanagement.repository.InformationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class InformationService {
    @Autowired
    private InformationRepository informationRepository;

    public List<Information> getAllInformation() {
        return informationRepository.findAll();
    }

    public Optional<Information> getInformationById(Long id) {
        return informationRepository.findById(id);
    }

    public Information saveInformation(Information information) {
        return informationRepository.save(information);
    }

    public Information updateInformation(Long id, Information newInformation) {
        return informationRepository.findById(id)
                .map(information -> {
                    information.setUsername(newInformation.getUsername());
                    information.setTelephone(newInformation.getTelephone());
                    information.setQq(newInformation.getQq());
                    information.setAddress(newInformation.getAddress());
                    return informationRepository.save(information);
                })
                .orElseGet(() -> {
                    newInformation.setId(id);
                    return informationRepository.save(newInformation);
                });
    }

    public void deleteInformation(Long id) {
        informationRepository.deleteById(id);
    }
}